package com.example.upload;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@RestController
@RequestMapping("/api/upload")
public class FileUploadController {

    @Value("${file.upload-dir}")
    private String uploadDir;

    @PostMapping
    public String handleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
        if (file.isEmpty()) {
            return "Please select a file to upload.";
        }

        try {
            // 生成UUID文件名
            String uuid = UUID.randomUUID().toString();
            String extension = getFileExtension(file.getOriginalFilename());
            String newFileName = uuid + "." + extension;
            Path path = Paths.get(uploadDir + File.separator + newFileName);

            // 确保目录存在
            Files.createDirectories(path.getParent());

            // 保存文件
            Files.copy(file.getInputStream(), path);

            return "You successfully uploaded " + newFileName + "!";
        } catch (IOException e) {
            e.printStackTrace();
            return "Failed to upload file!";
        }
    }

    // 辅助方法：获取文件扩展名
    private String getFileExtension(String fileName) {
        if (fileName == null || fileName.isEmpty()) {
            return "";
        }
        int dotIndex = fileName.lastIndexOf('.');
        return dotIndex == -1 ? "" : fileName.substring(dotIndex + 1);
    }
}
